<?php
/**
 * Created by PhpStorm.
 * User: marek
 * Date: 25/10/13
 * Time: 22:27
 */
namespace Jhub1_Admin\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\JsonModel;
use Zend\View\Model\ViewModel;
use Jhub1_Admin\Form\Login;
use Jhub1_Admin\Model\FormFilter\LoginFilter;
use Jhub1_Common\Model\Endpoint\Prototype\Integer as Integer;
use Jhub1_Common\Entity\BO\UsersBO;
use Zend\Session\Container;
use Jhub1_Common\Model\KeyGenerator;
use Zend\Form\Annotation\AnnotationBuilder;
use Zend\Stdlib\ArrayObject;

class AuthenticateController extends AbstractActionController
{
    public function indexAction()
    {
/*        $em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
        $user = $em->getRepository('\Application\Entity\OfUser')->find('user1');
*/
        $loginForm    = new Login();
        $builder    = new AnnotationBuilder();
        $form       = $builder->createForm($loginForm);
        $request = $this->getRequest();
        if ($request->isPost()){
            $form->bind($loginForm);
            $form->setData($request->getPost());
            if ($form->isValid()){
                $userBO = new UsersBO($this->getServiceLocator());
                $existUserPO = $userBO->getUserByEmailAndPassword($loginForm->getEmail(), $loginForm->getPassword());
                if (null == $existUserPO) {
                    $result = new JsonModel(array(
                        'form_messages' => '',
                        'general_messages' => 'Sorry but your username and password do not match',
                        'success'=>false,
                    ));
                    return $result;
                } else if($existUserPO->getStatus() == 0) {
                    //generate Resend Email code
                    $kg = new KeyGenerator();
                    $resendCode = $kg->genKey(30);
                    $userBO->setResendCode($existUserPO, $resendCode);
                    $result = new JsonModel(array(
                        'form_messages' => '',
                        'general_messages' => 'The account has not been activated please click %s this link %s to have the activation email resent.',
                        'code' => $resendCode,
                        'success'=> false,
                    ));
                    return $result;
                }
                $session_user = new Container('user');
                $session_user->offsetSet('userobject', $existUserPO);
                $userBO->updateLastLoginDate($existUserPO);
                // Successful login Redirect to list control panel
                $result = new JsonModel(array(
                    'form_messages' => '',
                    'general_messages' => '',
                    'code' => '',
                    'redirect' => '/dgfg/dgg',
                    'success'=> true,
                ));
                return $result;
          //      return $this->redirect()->toRoute('hub', array('action' => 'index'));
            } else {
                $result = new JsonModel(array(
                    'form_messages' => $form->getMessages(),
                    'general_messages' => '',
                    'success'=>false,
                ));

                return $result;
            }
        }
        $results = new ViewModel();
        $results->setTerminal(true);
        $results->setVariables(array('form' => $form));
        return $results;

/*        $form = new Login();
        $request = $this->getRequest();
        if ($request->isPost()) {
            $loginFilter = new LoginFilter();
            $form->setInputFilter($loginFilter->getInputFilter());
            $form->setData($request->getPost());
            if ($form->isValid()) {
                $userBO = new UsersBO($this->getServiceLocator());
                $formData = $form->getData();
                $loginFilter->exchangeArray($form->getData());
                $existUserPO = $userBO->getUserByEmailAndPassword($formData['email'], $formData['password']);
                if (null == $existUserPO) {
                    return array('error' => true,
                        'statusMessage' => 'Sorry but your username and password do not match',
                    );
                } else if($existUserPO->getStatus() == 0) {
                    //generate Resend Email code
                    $kg = new KeyGenerator();
                    $resendCode = $kg->genKey(30);
                    $userBO->setResendCode($existUserPO, $resendCode);
                    return array('error' => true,
                        'statusMessage' => 'The account has not been activated please click %s this link %s to have the activation email resent.',
                        'code' => $resendCode
                    );
                }
                $session_user = new Container('user');
                $session_user->offsetSet('userobject', $existUserPO);
                $userBO->updateLastLoginDate($existUserPO);
                // Successful login Redirect to list control panel
                return $this->redirect()->toRoute('hub', array('action' => 'index'));
            } else {
                return array('error' => true,
                    'formData' => $form->getData(),
                    'formMessages' => $form->getMessages()
                );
            }
        }
        return array('form' => $form);*/
   #     } else {
     #       return $this->redirect()->toRoute('home');
      #  }
    }

    public function index2Action()
    {
        /*        $em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
                $user = $em->getRepository('\Application\Entity\OfUser')->find('user1');
                echo $user->getName();
                die;*/
        #     if (!$this->authCheck()->isValid()) {
        $form = new Login();
        $request = $this->getRequest();
        if ($request->isPost()) {
            $loginFilter = new LoginFilter();
            $form->setInputFilter($loginFilter->getInputFilter());
            $form->setData($request->getPost());
            if ($form->isValid()) {
                $userBO = new UsersBO($this->getServiceLocator());
                $formData = $form->getData();
                $loginFilter->exchangeArray($form->getData());
                $existUserPO = $userBO->getUserByEmailAndPassword($formData['email'], $formData['password']);
                if (null == $existUserPO) {
                    return array('error' => true,
                        'statusMessage' => 'Sorry but your username and password do not match',
                    );
                } else if($existUserPO->getStatus() == 0) {
                    //generate Resend Email code
                    $kg = new KeyGenerator();
                    $resendCode = $kg->genKey(30);
                    $userBO->setResendCode($existUserPO, $resendCode);
                    return array('error' => true,
                        'statusMessage' => 'The account has not been activated please click %s this link %s to have the activation email resent.',
                        'code' => $resendCode
                    );
                }
                $session_user = new Container('user');
                $session_user->offsetSet('userobject', $existUserPO);
                $userBO->updateLastLoginDate($existUserPO);
                // Successful login Redirect to list control panel
                return $this->redirect()->toRoute('hub', array('action' => 'index'));
            } else {
                return array('error' => true,
                    'formData' => $form->getData(),
                    'formMessages' => $form->getMessages()
                );
            }
        }
        return array('form' => $form);
        #     } else {
        #       return $this->redirect()->toRoute('home');
        #  }
    }

    public function logoutAction()
    {
        $session_user = new Container('user');
        $session_user->getManager()->getStorage()->clear('user');
        return $this->redirect()->toRoute('home');
    }

    public function facebookAction()
    {
     //   $builder = new AnnotationBuilder();
     //   $form    = $builder->createForm('Application\Model\Endpoint\Prototype\Integer');

        $integer    = new Integer();
        $builder    = new AnnotationBuilder();
        $form       = $builder->createForm($integer);
        $request = $this->getRequest();
        if ($request->isPost()){
            $form->bind($integer);
            print_r($request->getPost());
            $form->setData($request->getPost());
            if ($form->isValid()){
                print_r($form->getData());
            }
        } else {
          //  populate the values here from object
            $contact = array();
            $contact['unit'] = 'rrrrr';
            $contact['maxlimit'] = 'uuuuu';
            $contact['minlimit'] = 'nnnnnnn';
            $contact['maxvalue'] = 'aaaaa';
            $form->setData($contact);
        }

        return new ViewModel(array('form' => $form));
    }

    public function googleplusAction()
    {
        return new ViewModel();
    }

    public function tweeterAction()
    {
        return new ViewModel();
    }

}